import React, {useState} from "react";
import {useNavigate} from "react-router-dom";

import { connect } from 'react-redux';

import {MenuFoldOutlined, MenuUnfoldOutlined, UserOutlined} from "@ant-design/icons";
import {Layout, Dropdown, Menu, Button} from "antd";

const { Header } = Layout;


function TopHeader(props) {
    // console.log(props)
    const navigate= useNavigate();
    const { role: { roleName }, username }= JSON.parse(localStorage.getItem('token'));
    const menu = (
        <Menu
            items={[
                {
                    key: '1',
                    label: roleName,
                    disabled: true
                },
                {
                    key: '2',
                    label: '退出',
                    onClick: ()=> {
                        localStorage.removeItem('token');
                        navigate('/login');
                    }
                }
            ]}
        />
    );

    // const [collapsed, setCollapsed] = useState(false);
    const changeCollapsedState= ()=>{
        // setCollapsed(!collapsed)

        // 改变redux state中的isCollapsed
        props.changeCollapsed();
    }

    return (
        <Header className="site-layout-background" style={{ padding: '0 16px'  }}>
            {/*{React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                className: 'trigger',
                onClick: () => setCollapsed(!collapsed),
            })}*/}

            {
                props.isCollapsed
                    ? <MenuFoldOutlined className='trigger'  onClick={changeCollapsedState}/>
                    : <MenuUnfoldOutlined className='trigger' onClick={changeCollapsedState}/>
            }

            <div style={{float: 'right'}}>
                <span style={{marginRight: '6px'}}>欢迎<span style={{color: '#1890ff', padding: '0 4px'}}>{username}</span>回来</span>
                <Dropdown overlay={menu} >
                    <Button type="ghost" shape="circle" size="small" icon={<UserOutlined />} />
                </Dropdown>
            </div>
        </Header>
    );
}

// export default TopHeader;


/*
 connect(
    mapStateToProps,
    mapDispatchToProps
 )(被包装组件)
 */
const mapStateToProps= (state)=>{
    // console.log(state)
    return {
        isCollapsed: state.collapsedReducer.isCollapsed
    }
}
const mapDispatchToProps= {
    // changeCollapsed: ()=>{
    changeCollapsed() {
        // 返回 action
        return {
            type: 'change_collapsed',
            // payload: true
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(TopHeader);
